package com.retailshop.shopuser.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.retailshop.shopuser.common.HsUserUtil;
import com.retailshop.shopuser.common.HttpPost;
import com.retailshop.shopuser.entity.HttpRequestConfig;
import com.retailshop.shopuser.entity.RedisUserNo;
import com.retailshop.shopuser.entity.User;
import com.retailshop.shopuser.entity.UserNo;
import com.retailshop.shopuser.entity.hsys.HsysUserData;
import com.retailshop.shopuser.entity.hsys.HsysUserRoot;
import com.retailshop.shopuser.service.HsUserService;
import com.retailshop.shopuser.service.UserNoService;
import com.retailshop.shopuser.service.UserRedisService;
import com.retailshop.shopuser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;

@Service("HsUserService")
public class HsUserServiceImpl implements HsUserService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserService userService;

    @Autowired
    UserNoService userNoService;

    @Autowired
    UserRedisService userRedisService;

    /*同步用户数据*/
    @Override
    public String syncUser(String startTime, String endTime) {
        System.out.println("startTime:" + startTime);
        System.out.println("endTime:" + endTime);

        String json = HsUserUtil.getHsUser(startTime, endTime);

        System.out.println("json:" + json);

        HsysUserRoot hsysUserRoot = JSON.parseObject(json, HsysUserRoot.class);
        List<HsysUserData> hsysUserList = hsysUserRoot.getData();

        System.out.println("数量:" + hsysUserList.size());

        for (int i = 0; i < hsysUserList.size(); i++) {
            HsysUserData hsysUser = hsysUserList.get(i);
            System.out.println("开始同步：" + hsysUser.getUserno() + "(" + hsysUser.getUsername() + ")");
            //查询是否存在手机号
            //如果存在，则返回ID号
            int userId = 0;

            /*读取用户信息-手机*/

            System.out.println("C");

            System.out.println("phone:" + hsysUser.getCellphone());

            Object redisPhone = redisTemplate.opsForValue().get("P" + hsysUser.getCellphone());

            Timestamp ts = new Timestamp(System.currentTimeMillis());
            String tsStr = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(hsysUser.getCreatetime());
            System.out.println(tsStr);
            try {
                ts = Timestamp.valueOf(tsStr);
                System.out.println(ts);
            } catch (Exception e) {
                e.printStackTrace();
            }

            RedisUserNo redisUserNo = JSON.parseObject(redisPhone == null ? null : redisPhone.toString(), new TypeReference<RedisUserNo>() {
            });
            if (redisUserNo != null) {
                System.out.println("A");
                userId = redisUserNo.getUserId();
                System.out.println("userId:" + userId);
            } else {
                System.out.println("B");
                User user = new User();
                user.setPhone(hsysUser.getCellphone());
                user.setCardid(hsysUser.getIdcard());
                user.setName(hsysUser.getUsername());
                user.setBirthday(ts);
                if (userService.insertSelective(user) > 0) {
                    userId = user.getId();
                }
            }

            System.out.println("UserId:" + userId);

            if (userId > 0) {
                System.out.println("BB:"+"US" + hsysUser.getUserno());
                /*读取用户信息-编号*/
                Object redisUserno = redisTemplate.opsForValue().get("US" + hsysUser.getUserno());
                RedisUserNo redisUserNo1 = JSON.parseObject(redisUserno == null ? null : redisUserno.toString(), new TypeReference<RedisUserNo>() {
                });
                if (redisUserNo1 == null) {
                    System.out.println("BC");

                    int rank = 0;
                    boolean agent = false;
                    switch (hsysUser.getLevel()) {
                        case 0:
                            rank = 1;
                            break;
                        case 1:
                            rank = 2;
                            agent = true;
                            break;
                        case 2:
                            rank = 3;
                            agent = true;
                            break;
                        case 10:
                            rank = 3;
                            agent = true;
                            break;
                        case 20:
                            rank = 4;
                            agent = true;
                            break;
                        case 30:
                            rank = 5;
                            agent = true;
                            break;
                        case 40:
                            agent = true;
                            rank = 5;
                            break;
                        case 401:
                            agent = true;
                            rank = 5;
                            break;
                        default:
                            rank = -1;
                            //rank = 1000+hsysUser.getLevel();
                            break;
                    }

                    UserNo userNo = new UserNo();
                    userNo.setNick(hsysUser.getUsername());
                    userNo.setNo(hsysUser.getUserno());
                    userNo.setUserId(userId);
                    userNo.setRankId(rank);
                    userNo.setAgent(agent);

                    userNo.setRegisterTime(ts);
                    userNo.setSort(Short.parseShort(100 + ""));
                    //处理分享人
                    int recommend = 0;
                    //查找是否存在分享人

                    /*读取用户信息-编号*/
                    Object redisAngel = redisTemplate.opsForValue().get("US" + hsysUser.getAngeluserno());
                    RedisUserNo redisUserNo2 = JSON.parseObject(redisAngel == null ? null : redisAngel.toString(), new TypeReference<RedisUserNo>() {
                    });

                    if (redisUserNo2 != null) {
                        recommend = redisUserNo2.getId();
                        System.out.println("用户分享ID" + recommend);
                    }
                    userNo.setShare(recommend);
                    userNo.setHsrank(hsysUser.getLevel());
                    userNoService.insertSelective(userNo);
                    int usernoId = userNo.getId();
                    if (usernoId > 0) {
                        //写入代金券
                        //返代金券
                        double amount = 0;
                        switch (hsysUser.getLevel()) {
                            case 1:
                                amount = 500;
                                break;
                            case 2:
                                amount = 1000;
                                break;
                            case 10:
                                amount = 4500;
                                break;
                            case 20:
                                amount = 12000;
                                break;
                            case 30:
                                amount = 45000;
                                break;
                            case 40:
                                amount = 90000;
                                break;
                            default:
                                break;
                        }

                        String shareRes = HttpPost.GetMod(HttpRequestConfig.finaceServerUrl, "/Finace/Add", "classify=3&type=360&state=1&userId=" + usernoId + "&UID="+usernoId+"&amount=" + amount + "&remark=注册赠送");
//                    JSONObject shareResJSON = JSONObject.parseObject(shareRes);
//                    String msgCode = shareResJSON.get("code").toString();
//                    if (!msgCode.equals("000000")) {//如果失败
//                        return false;
//                    }
                        System.out.println(shareRes);

                        //写缓存
                        userRedisService.setRedisUserAll();
                    }
                }
                else{
                    System.out.println("BD");
                    System.out.println("redisUserNo:"+redisUserNo.getNo());
                }

            }
        }


        return json;
    }

}
